# coding:utf-8

import json
from old_version.src.util.TimeUtil import TimeUtil
from old_version.src.util.RedisUtil import RedisUtil
from old_version.src.util.HttpUtil import HttpUtil
from old_version.src import StockIndex
from hbase.ttypes import *


class StockIndexService:

    def __init__(self):
        pass

    # '''
    # 0000001,1399001,1399005,1399006
    # '''
    # def put_stock_index_metadata(self):
    #     HbaseUtil.socket.open()
    #
    #     batch_mutation_list = list()
    #
    #     # 上证指数
    #     mutation_list = list()
    #     mutation_list.append(Mutation(column="info:id", value="0000001"))
    #     mutation_list.append(Mutation(column="info:code", value="000001"))
    #     mutation_list.append(Mutation(column="info:name", value="上证指数"))
    #     batch_mutation = BatchMutation("0000001", mutation_list)
    #     batch_mutation_list.append(batch_mutation)
    #
    #     # 深证成指
    #     mutation_list = list()
    #     mutation_list.append(Mutation(column="info:id", value="1399001"))
    #     mutation_list.append(Mutation(column="info:code", value="399001"))
    #     mutation_list.append(Mutation(column="info:name", value="深证成指"))
    #     batch_mutation = BatchMutation("1399001", mutation_list)
    #     batch_mutation_list.append(batch_mutation)
    #
    #     # 中小板指
    #     mutation_list = list()
    #     mutation_list.append(Mutation(column="info:id", value="1399005"))
    #     mutation_list.append(Mutation(column="info:code", value="399005"))
    #     mutation_list.append(Mutation(column="info:name", value="中小板指"))
    #     batch_mutation = BatchMutation("1399005", mutation_list)
    #     batch_mutation_list.append(batch_mutation)
    #
    #     # 创业板指
    #     mutation_list = list()
    #     mutation_list.append(Mutation(column="info:id", value="1399006"))
    #     mutation_list.append(Mutation(column="info:code", value="399006"))
    #     mutation_list.append(Mutation(column="info:name", value="创业板指"))
    #     batch_mutation = BatchMutation("1399006", mutation_list)
    #     batch_mutation_list.append(batch_mutation)
    #
    #     HbaseUtil.client.mutateRows("stock_index", batch_mutation_list)
    #     HbaseUtil.socket.close()


    '''
    从网络上采集股票指数数据，首先存储在redis集群中，然后再存储在stock_index.json文件中
    '''
    def collect_stock_index(self):
        print(TimeUtil.date(), "collect_stock_index method start")
        stock_index_metadata_list = ["0000001","1399001","1399005","1399006"]
        stock_index_list = list()
        f = open("/stock_index.json", "a+")
        for stock_index_metadata in stock_index_metadata_list:
            param = "code=" + stock_index_metadata + "&start=20180501&end=20180531&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP"
            result = HttpUtil.get_data("http://quotes.money.163.com/service/chddata.html", param)
            row_list = result.split("\n")
            for index, name in enumerate(row_list):
                # 第一行数据不采集
                if index == 0:
                    continue
                # 到达末尾就返回
                if len(row_list) - 1 <= index:
                    break
                column_list = name.split(",")

                stock_index = StockIndex()
                stock_index.date = column_list[0].replace("-", "").encode("utf-8")
                stock_index.id = column_list[1][1:].encode("utf-8")
                # # the first char of code is ', so it should be deleted
                stock_index.code = column_list[1][1:].encode("utf-8")
                stock_index.name = column_list[2].encode("utf-8")
                stock_index.close = column_list[3].encode("utf-8")
                stock_index.high = column_list[4].encode("utf-8")
                stock_index.low = column_list[5].encode("utf-8")
                stock_index.open = column_list[6].encode("utf-8")
                stock_index.last_close = column_list[7].encode("utf-8")
                stock_index.up_down_amount = column_list[8].encode("utf-8")
                stock_index.up_down = str(1) if stock_index.up_down_amount > str(0) else str(-1)
                stock_index.up_down_percentage = column_list[9].encode("utf-8")
                stock_index.volume = column_list[11].encode("utf-8")
                stock_index.amount = column_list[12].encode("utf-8")
                # 将stock_index对象保存在stock_index_list中，以便以后批量插入到redis集群中
                stock_index_list.append(stock_index)
                # 将stock_index对象装换为json字符串
                json_str = json.dumps(stock_index.__dict__, encoding='UTF-8', ensure_ascii=False)
                # 将stock_record的json字符串追加到文件stock_record.json中
                f.write((json_str + "\n").encode("utf-8"))

        # 将stock_record_list数组批量加入到redis集群中
        RedisUtil.put_stock_index_list(stock_index_list)
        f.close()

    '''
    计算上证指数，深证成指，中小板指数和创业板指数的hei kin ashi的开盘价，收盘价，最高价和最低价
    '''
    def calculate_stock_index_ha(self):
        print(TimeUtil.date(), "calculate_stock_index_ha method start")
        stock_index_code_list = ['000001', '399001', '399005', '399006']
        for stock_index_code in stock_index_code_list:
            stock_index_list = RedisUtil.redis_conn.zrange("StockIndex_"+stock_index_code, 0, -1, withscores=True)
            for index, value in enumerate(stock_index_list):
                # 需要有两个对象，一个指向前一天的记录，另一个指向当天的记录
                if index == 0:
                    former_stock_index_build = json.loads(value[0])
                    former_stock_index_object = StockIndex()
                    former_stock_index_object.__dict__ = former_stock_index_build
                    continue
                stock_index_build = json.loads(value[0])
                stock_index_object = StockIndex()
                stock_index_object.__dict__ = stock_index_build

                # 计算hei kin ashi平均K线开盘价，收盘价，最高价和最低价
                stock_index_object.ha_open = (float(former_stock_index_object.open.encode("utf-8")) +
                                              float(former_stock_index_object.close.encode("utf-8"))) / 2
                stock_index_object.ha_close = (float(stock_index_object.open.encode("utf-8")) +
                                               float(stock_index_object.close.encode("utf-8")) +
                                               float(stock_index_object.high.encode("utf-8")) +
                                               float(stock_index_object.low.encode("utf-8"))) / 4
                stock_index_object.ha_high = self.max_value(float(stock_index_object.high.encode("utf-8")),
                                                            float(stock_index_object.open.encode("utf-8")),
                                                            float(stock_index_object.close.encode("utf-8")))
                stock_index_object.ha_low = self.min_value(float(stock_index_object.low.encode("utf-8")),
                                                           float(stock_index_object.open.encode("utf-8")),
                                                           float(stock_index_object.close.encode("utf-8")))

                new_json_str = json.dumps(stock_index_object.__dict__, encoding='UTF-8',
                                          ensure_ascii=False).encode("utf-8")
                # 经过json.dumps和json.loads方法后的json字符串虽然内容一样，但是顺序不一样了
                old_json_str = value[0]
                RedisUtil.redis_conn.zrem("StockIndex_"+stock_index_object.code.encode("utf-8"), old_json_str)
                RedisUtil.redis_conn.zadd("StockIndex_"+stock_index_object.code.encode("utf-8"),
                                          stock_index_object.date.encode("utf-8"),
                                          new_json_str)




if __name__ == "__main__":
    pass

